package com.lovestudying.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class CharacterEncodingFilter
 */
public class CharacterEncodingFilter implements Filter {
	
	// 初始化
	private static String encoding = null;
	private static String contentType = null;
    /**
     * Default constructor. 
     */
    public CharacterEncodingFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest req = (HttpServletRequest) request;
		StringBuffer requestURL = req.getRequestURL();
		
		if(requestURL.toString().endsWith(".css")) {
			chain.doFilter(request, response);
		}else {
			if(encoding != null && contentType != null) {
				// 设置请求编码格式
				request.setCharacterEncoding(encoding);
				
				// 设置响应编码格式
				response.setContentType(contentType);
				response.setCharacterEncoding(encoding);
			} 
			chain.doFilter(request, response);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// 获取初始化参数
		encoding = fConfig.getInitParameter("encoding");
		contentType = fConfig.getInitParameter("contentType");
	}

}
